package com.hejx.managecenter.web.interceptor;

import com.hejx.managecenter.common.bean.Result;
import com.hejx.managecenter.common.enums.ResultEnum;
import com.hejx.managecenter.common.utils.GsonUtils;
import com.hejx.managecenter.common.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: managecenter_example
 * @description: 登录拦截器
 * @author: hejx
 * @email: doubihah@foxmail.com
 * @create: 2018-06-24 11:10
 **/
public class LoginSessionInterceptor implements HandlerInterceptor {

    @Value("${login_page}")
    private String LOGIN_PAGE;

    /**
     * 验证策略：有token则先走token 再走sessionUser
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String agent = request.getHeader("User-agent");
        String servletPath = request.getServletPath();
        String token = request.getParameter("token");
        request.getSession().setAttribute("user","");
//        UserVo user = null;
//        if(StringUtils.isBlank(token)){
//            user = restService.getUserByToken(token);
//            if(user == null){
//                noAuth(request,response);
//                return false;
//            }
//            if(user.getMenulist() == null){
////                restService.logout(token);
//                response.sendRedirect("/403");
//                return false;
//            }else{
//                request.getSession().setAttribute("user",user);
//                return true;
//            }
//        }else{ // token is null
//            user = (UserVo) request.getSession().getAttribute("user");
//        }
//        if(user == null){
//            noAuth(request,response);
//            return false;
//        }
        return true;    //如果false，停止流程，api被拦截
    }

    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
//        System.out.println("postHandle被调用");
    }

    //在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
//        System.out.println("afterCompletion被调用");
    }

    /**
     * 没有授权访问
     */
    private void noAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String servletPath = request.getServletPath();
        if(isAjaxRequest(request)){
            Result result = ResultUtil.error(ResultEnum.TOKEN_INVALID);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type", "application/json");
            response.getWriter().print(GsonUtils.objToJson(result));
        }else{
            response.sendRedirect(LOGIN_PAGE);
        }
    }

    private boolean isAjaxRequest(HttpServletRequest request){
        String requestType = request.getHeader("X-Requested-With");
        if("XMLHttpRequest".equals(requestType)){
//            System.out.println("AJAX请求..");
            return true;
        }else{
            //此时requestType为null
//            System.out.println("非AJAX请求..");
            return false;
        }
    }

}
